/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GastoSegunObjetoListar.java
 *
 * Created on 07/03/2011, 04:21:53 PM
 */
package org.gingresos.regimenimpositivo;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.gingresosapi.beans.*;
import org.gingresosapi.controller.*;
import org.gingresosapi.generales.Mensajeria;
import org.gingresos.start.MySesion;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
/**
 *
 * @author avbravo
 */
public class DefinirIngresosTributarios extends javax.swing.JInternalFrame {

    DefaultTableModel modelo;
    int fila = -1;
    GruporegimenController gruporegimenController1;
    Gruporegimen gruporegimen1;
    String nombreGrupoRegimen = "";
    JComboBox comboTipo;
    int filas;

    /** Creates new form GastoSegunObjetoListar */
    public DefinirIngresosTributarios() {
        initComponents();
        gruporegimenController1 = new GruporegimenController();
        gruporegimen1 = new Gruporegimen();
        modelo = (DefaultTableModel) jXTable1.getModel();
        CargarTabla();
       
               comboTipo = new JComboBox();
        comboTipo.addItem("Tributario");
        comboTipo.addItem("No Tributario");
        comboTipo.addItem("Saldo en Caja");
        comboTipo.addItem("Recursos de Patrimonio");
        comboTipo.addItem("Venta de Terreno");

        TableColumn column = jXTable1.getColumnModel().getColumn(2);
        column.setPreferredWidth(30);
        column.setCellEditor(new DefaultCellEditor(comboTipo));
        comboTipo.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ComboTipoAction(evt);
            }
        });

    }

    private void CargarTabla(){
        try{
             if (gruporegimenController1.selectAll()) {
            Object[] filas = new Object[3]; // Hay tres columnas en la tabla
            for (Gruporegimen g : gruporegimenController1.getGruporegimenlist()) {

                filas[0] = g.getIdgruporegimen();
                filas[1] = g.getGrupo();
               filas[2] = g.getTipo();


                modelo.addRow(filas);

            }
            
        }
      
        }catch(Exception ex){
            Mensajeria.MensajeError(ex, "CargarTabla()");
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jXTable1 = new org.jdesktop.swingx.JXTable();
        jButtonImprimir = new javax.swing.JButton();
        jButtonCerrar = new javax.swing.JButton();
        jButtonGuardar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Definir Ingresos Tributarios");

        jXTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Grupo", "Corriente"
            }
        ));
        jScrollPane1.setViewportView(jXTable1);

        jButtonImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/print.png"))); // NOI18N
        jButtonImprimir.setToolTipText("Guardar");
        jButtonImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImprimirActionPerformed(evt);
            }
        });

        jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/return.png"))); // NOI18N
        jButtonCerrar.setToolTipText("Cerrar");
        jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCerrarActionPerformed(evt);
            }
        });

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/save.gif"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 674, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(190, 190, 190)
                .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(jButtonImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(jButtonCerrar, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
                .addGap(191, 191, 191))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)
                    .addComponent(jButtonCerrar, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE)
                    .addComponent(jButtonImprimir, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE))
                .addGap(40, 40, 40))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        getAccessibleContext().setAccessibleName("Sub Grupo Regimen Listar");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ComboTipoAction(java.awt.event.ActionEvent evt) {
        try {
//           filas = jXTable1.getSelectedRow();
//           if (filas == -1) {
//               return;
//           }
//          comboCapital.setSelectedItem("---");
//        
        } catch (Exception ex) {
        }
    }

    private void ComboCapitalAction(java.awt.event.ActionEvent evt) {
        try {
//            filas = jXTable1.getSelectedRow();
//           if (filas == -1) {
//               return;
//           }
//          comboTipo.setSelectedItem("---");
        } catch (Exception ex) {
        }


    }
private void jButtonImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImprimirActionPerformed
// TODO add your handling code here:
    try {
        HashMap map = new HashMap();
        map.put("p_municipio", MySesion.getMunicipio());
       gruporegimenController1.selectAll();
        Imprimir(gruporegimenController1.getGruporegimenlist(), map);
        jButtonGuardar.setEnabled(false);
    } catch (Exception ex) {
        Mensajeria.MensajeError(ex, "Imprimir()");
    }
}//GEN-LAST:event_jButtonImprimirActionPerformed

private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
// TODO add your handling code here:
    dispose();
}//GEN-LAST:event_jButtonCerrarActionPerformed

    private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
        try {
            int contador =0;
            int n = jXTable1.getRowCount();
            if (n == 0) {
                Mensajeria.Mensaje("No existe ninguna fila en la tabla");
                return;
            }
            String idgruporegimen;
            String tipo;
            for (int i = 0; i < n; i++) {
                  idgruporegimen = jXTable1.getValueAt(i, 0).toString();
                if(jXTable1.getValueAt(i, 2).toString()== null ||jXTable1.getValueAt(i, 2).toString().equals("")){
                   
                    tipo="sin definir";
                    contador++;
                }else{
                     tipo = jXTable1.getValueAt(i, 2).toString();
                }
                
                              
                gruporegimen1.setIdgruporegimen(idgruporegimen);
                if (gruporegimenController1.findByIdgruporegimen(gruporegimen1)) {
                   
                    gruporegimen1 = gruporegimenController1.getGruporegimenlist().get(0);
                   
                    gruporegimen1.setTipo(tipo);
                  
                    if (gruporegimenController1.update(gruporegimen1)) {
                       
                    }
                }
            }
            String mensaje="";
            if(contador !=0){
                mensaje="Pero aun hay grupos sin definir";
            }
            Mensajeria.Mensaje("Se actualizaron los registros "+mensaje);
         jButtonGuardar.setEnabled(false);
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Guardar()");
        }


    }//GEN-LAST:event_jButtonGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new GastoSegunObjetoListar().setVisible(true);
//            }
//        });
//    }
    private void Imprimir(List<Gruporegimen> aux, HashMap map) throws JRException {
        try {
            JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(aux);
            InputStream reporte;

            reporte = (InputStream) getClass().getResourceAsStream("/org/gingresos/reportes/regimen/Gruporegimen.jasper");

            if (reporte == null) {
                Mensajeria.Mensaje("No se pudo cargar el reporte");
            } else {
                JasperPrint print = JasperFillManager.fillReport(reporte, map, ds);
                JasperViewer.viewReport(print, false);
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Imprimir()");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCerrar;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonImprimir;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable jXTable1;
    // End of variables declaration//GEN-END:variables
}
